package com.hliushi.learn.utils;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;

/**
 * @author llhuang10
 * @date 2021/7/21 16:05
 */
@Slf4j
public class IpUtil {


    /**
     * 数据库地址
     */
    public static final String IP_DB_PATH = "GeoLite2-City.mmdb";

    @Value("${amap.key}")
    public static String AMAP_KEY;

    public static DatabaseReader READER;

    static {
        try {
            READER = new DatabaseReader.Builder(IpUtil.class.getClassLoader()
                    .getResourceAsStream(IP_DB_PATH)).build();
        } catch (Exception e) {
            log.error("IP地址服务初始化异常: " + e.getMessage(), e);
            // throw new RuntimeException("IP地址服务初始化异常:" + e);
        }
    }

    /**
     * 私有构造器, 任何时候都不会实例化!
     */
    private IpUtil() {

    }


    /**
     * 获取国家
     *
     * @param ip ip
     * @return
     */
    public static String getCountry(String ip) {
        try {
            return READER.city(InetAddress.getByName(ip)).getCountry().getNames().get("zh-CN");
        } catch (IOException | GeoIp2Exception e) {
            log.error("根据IP[{}]获取国家失败:{}", ip, e.getMessage());
            return null;
        }
    }

    /**
     * 获取身份
     *
     * @param ip ip
     * @return
     */
    public static String getProvince(String ip) {
        try {
            return READER.city(InetAddress.getByName(ip)).getMostSpecificSubdivision().getNames().get("zh-CN");
        } catch (IOException | GeoIp2Exception e) {
            log.error("根据IP[{}]获取省份失败:{}", ip, e.getMessage());
            return null;
        }
    }

    public static String getProvince2(String ip) {
        try {
            return READER.city(InetAddress.getByName(ip)).getMostSpecificSubdivision().getNames().get("zh-CN");
        } catch (IOException | GeoIp2Exception e) {
            log.error("根据IP[{}]获取省份失败:{}", ip, e.getMessage());
            return null;
        }
    }

    /**
     * 获取城市
     *
     * @param ip ip
     * @return
     */
    public static String getCity(String ip) {
        try {
            return READER.city(InetAddress.getByName(ip)).getCity().getNames().get("zh-CN");
        } catch (IOException | GeoIp2Exception e) {
            log.error("根据IP[{}]获取城市失败:{}", ip, e.getMessage());
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        // 创建 GeoLite2 数据库
        File database = new File("D:\\IdeaProjects\\springboot-demo\\springboot_learn\\src\\main\\resources\\GeoLite2-City.mmdb");
        // 读取数据库内容
        DatabaseReader reader = new DatabaseReader.Builder(database).build();
        // InetAddress ipAddress = InetAddress.getByName("171.108.233.157");
        InetAddress ipAddress = InetAddress.getByName("1.15.154.233");

        // 获取查询结果
        CityResponse response = reader.city(ipAddress);

        // 获取国家信息
        Country country = response.getCountry();
        System.out.println(country.getIsoCode());               // 'CN'
        System.out.println(country.getName());                  // 'China'
        System.out.println(country.getNames().get("zh-CN"));    // '中国'

        // 获取省份
        Subdivision subdivision = response.getMostSpecificSubdivision();
        System.out.println(subdivision.getName());   // 'Guangxi Zhuangzu Zizhiqu'
        System.out.println(subdivision.getIsoCode()); // '45'
        System.out.println(subdivision.getNames().get("zh-CN")); // '广西壮族自治区'

        // 获取城市
        City city = response.getCity();
        System.out.println(city.getName()); // 'Nanning'
        Postal postal = response.getPostal();
        System.out.println(postal.getCode()); // 'null'
        System.out.println(city.getNames().get("zh-CN")); // '南宁'
        Location location = response.getLocation();
        System.out.println(location.getLatitude());  // 22.8167
        System.out.println(location.getLongitude()); // 108.3167
    }

}
